package school;

import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;

public class DateComparator implements Comparator<Date> {

	public final long millisADay = 60 * 60 * 24 *1000;

	@Override
	public int compare(Date date1, Date date2) {

		//if one of them is null, assume equal
		if (date1==null || date2==null) {
			return 0;
		}
		
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTime(date1);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(date2);

		if (Math.abs(calendar1.getTimeInMillis() - calendar2.getTimeInMillis()) > millisADay) {
			return calendar1.compareTo(calendar2);
		}
		
		calendar2.setTimeZone(calendar1.getTimeZone()); // sync time zone

		if (calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) {
			if (calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)) {
				if (calendar1.get(Calendar.DATE) == calendar2.get(Calendar.DATE)) {
					return 0;
				} else {
					return calendar1.get(Calendar.DATE) - calendar2.get(Calendar.DATE);
				}
			} else {
				return calendar1.get(Calendar.MONTH) - calendar2.get(Calendar.MONTH);
			}
		} else {
			return calendar1.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR);
		}
	}

}
